﻿using System;
using System.Net;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json.Linq;
using JDCloudSDK.Core.Auth;
using JDCloudSDK.Core.Extensions;
using TrinityAPI.Base;
using TrinityAPI.Base.Tools;
using TrinityAPI.Base.Models;

namespace JingDong.Open.Platform
{
    public class HuFuRequest : IAction
    {
        public JToken Invoke(JObject dataset, params JToken[] args)
        {
            var request = args.Length > 0 ? args[0] as JObject : dataset.GetJsonObject("request");
            var constant = dataset.GetJsonObject("constant");
            var jingdongHufuAPIConfig = constant.GetNecessaryJsonObject("jingdongHufuAPIConfig", "constant");

            string method = jingdongHufuAPIConfig.GetNecessaryJsonObjectStringValue("default_method", "constant.jingdongHufuAPIConfig");
            string url = jingdongHufuAPIConfig.GetNecessaryJsonObjectStringValue("url", "constant.jingdongHufuAPIConfig");
            string appkey = jingdongHufuAPIConfig.GetNecessaryJsonObjectStringValue("app_key", "constant.jingdongHufuAPIConfig");
            string appsecret = jingdongHufuAPIConfig.GetNecessaryJsonObjectStringValue("app_secret", "constant.jingdongHufuAPIConfig");
            string customerId = jingdongHufuAPIConfig.GetNecessaryJsonObjectStringValue("customerid", "constant.jingdongHufuAPIConfig");
            var proxy = jingdongHufuAPIConfig.GetJsonObjectValue("proxy");
            var logResponse = jingdongHufuAPIConfig.GetJsonObjectBooleanValue("logResponse", true);

            var credentials = new Credentials(appkey, appsecret);

            try
            {
                var proxyHttpClientHandler = new HttpClientHandler();

                if (proxy != null && proxy.Type == JTokenType.String && !string.IsNullOrWhiteSpace(proxy.ToString()) && proxy.ToString().IndexOf(":") > -1)
                {
                    string[] hostAndPort = proxy.ToString().Split(':');
                    int port = 0;
                    if (int.TryParse(hostAndPort[1], out port))
                    {
                        proxyHttpClientHandler.Proxy = new WebProxy(hostAndPort[0], port);
                        proxyHttpClientHandler.UseProxy = true;
                    }
                }
                else if (proxy != null && proxy.Type == JTokenType.Boolean && !proxy.Value<bool>())
                {
                    proxyHttpClientHandler.Proxy = null;
                    proxyHttpClientHandler.UseProxy = false;
                }

                string requestString = request?.ToString(Newtonsoft.Json.Formatting.None) ?? string.Empty;

                LogHelper.Info("url: " + url, "PlatformApiLog");
                LogHelper.Info("request: " + requestString, "PlatformApiLog");

                using (HttpClient httpClient = new HttpClient(proxyHttpClientHandler))
                {
                    string fullurl = string.Format(url + "?app_key={0}&customerId={1}&method={2}", appkey, customerId, method);
                    var content = new StringContent(requestString, Encoding.UTF8, "application/json");
                    var response = httpClient.DoSign(credentials, "xohk7ybhwien").PostAsync(fullurl, content).Result;
                    var responseString = response.Content?.ReadAsStringAsync().Result;

                    if (logResponse)
                        LogHelper.Info("response: " + responseString, "PlatformApiLog");

                    var responseObject = JObject.Parse(responseString);
                    if (responseObject.GetJsonObjectStringValue("code") != "0000")
                        throw ExceptionHelper.GenException("@E110011002", responseObject.GetJsonObjectStringValue("message"));

                    return responseObject.GetJsonObjectValue("extendProps");
                }
            }
            catch (BaseException ex)
            {
                var extendProps = request.GetJsonObject("extendProps");
                new SendEmail().Invoke(dataset, new JObject()
                {
                    { "subject", string.Format("【{0}】-【{1}】 get api data error", extendProps.GetJsonObjectStringValue("eShopCode"), extendProps.GetJsonObjectStringValue("method")) },
                    { "message", string.Format("{0}-{1}", ex.Code, ex.Message) }
                });
                if (!string.IsNullOrEmpty(ex.Message))
                    throw ex;
                throw new Exception(ex.Code);
            }
            catch (Exception ex)
            {
                var extendProps = request.GetJsonObject("extendProps");
                new SendEmail().Invoke(dataset, new JObject()
                {
                    { "subject", string.Format("【{0}】-【{1}】 get api data error", extendProps.GetJsonObjectStringValue("eShopCode"), extendProps.GetJsonObjectStringValue("method")) },
                    { "message", string.Format("{0}<br><br>{1}", ex.Message, ex.StackTrace) }
                });
                LogHelper.Error("JingDong HuFuRequest Fail", ex, "PlatformApiLog");
                throw new Exception("@E110011001");
            }
            
        }
    }
}
